package com.onlyxiahui.wofa.server.socket.netty.common.util;

import java.io.InputStream;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;

/**
 * Description <br>
 * Date 2021-01-08 15:24:17<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class SslContextUtil {

	public static SslContext createSslContext(String certificatePath, String keyPath, String keyPassword) throws Exception {
		SslContext sslContext = null;
		InputStream certificateInputStream = null;
		InputStream keyInputStream = null;
		try {

			PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
			Resource[] resources = resolver.getResources(certificatePath);

			if (resources != null && resources.length > 0) {
				Resource resource = resources[0];
				certificateInputStream = resource.getInputStream();
			}

			resources = resolver.getResources(keyPath);
			if (resources != null && resources.length > 0) {
				Resource resource = resources[0];
				keyInputStream = resource.getInputStream();
			}
			sslContext = SslContextBuilder.forServer(certificateInputStream, keyInputStream, keyPassword).build();

		} finally {
			if (null != certificateInputStream) {
				certificateInputStream.close();
			}
			if (null != keyInputStream) {
				keyInputStream.close();
			}
		}
		return sslContext;
	}
}
